package com.sgcc.pda.web;


import android.net.Uri;
import android.os.RemoteException;


import com.sgcc.pda.data.dao.SharepreferenceUtil;
import com.sgcc.pda.tools.LogPrintUtils;
import com.sgcc.pda.util.PlatConstant;
import com.sgcc.pda.util.DataConversionUtil;
import com.sgcc.platforminterface.PlatfInterfManager;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.util.List;
import java.util.Map;



/**
 * 网路服务管理类.
 *
 * @author 王沛栋
 * @data 2018/1/22 17:33
 */

public class OrigWebUtil {
    private static IWebManager mWebManager;

    private static IWebManager getWebManager() {
        if (mWebManager == null) {
            mWebManager = WebManager.getInstance().getWebManager();
        }
        return mWebManager;
    }


    public static void postData(String serverName, String methodName, String cmdName, Map<String, String> requestParams, String broadcastName) throws RemoteException {
        Uri.Builder builder = Uri.parse(cmdName).buildUpon();
        for (String key : requestParams.keySet()) {
            builder.appendQueryParameter(key, requestParams.get(key));
        }
        LogPrintUtils.d(builder.toString());
        LogPrintUtils.d("入参：", builder.toString());
        JSONObject jb = new JSONObject();
        try {
            String paramsHex = DataConversionUtil.str2HexStr(builder.toString());
            jb.put(PlatConstant.IWeb.SERVER_NAME, serverName);
            jb.put(PlatConstant.IWeb.REQUEST_PARM, paramsHex);
            jb.put(PlatConstant.IWeb.UID, SharepreferenceUtil.getUid(PlatfInterfManager.getInstance().getContext()));
            jb.put(PlatConstant.IWeb.MAC, SharepreferenceUtil.getMac(PlatfInterfManager.getInstance().getContext()));
        } catch (JSONException e) {
            e.printStackTrace();
        }
        getWebManager().postData(broadcastName, methodName, jb.toString());
    }

    /**
     * 发送参数
     * @param serverName
     * @param methodName
     * @param cmdName
     * @param requestParams
     * @param broadcastName
     * @param appendUid 是否添加UID
     * @throws RemoteException
     */
    public static void postData(String serverName, String methodName, String cmdName, Map<String, String> requestParams, String broadcastName, boolean appendUid) throws RemoteException {
        Uri.Builder builder = Uri.parse(cmdName).buildUpon();
        for (String key : requestParams.keySet()) {
            builder.appendQueryParameter(key, requestParams.get(key));
        }
        LogPrintUtils.d(builder.toString());
        LogPrintUtils.d("入参：", builder.toString());
        JSONObject jb = new JSONObject();
        try {
            String paramsHex = DataConversionUtil.str2HexStr(builder.toString());
            jb.put(PlatConstant.IWeb.SERVER_NAME, serverName);
            jb.put(PlatConstant.IWeb.REQUEST_PARM, paramsHex);
            if (appendUid) {
                jb.put(PlatConstant.IWeb.UID, SharepreferenceUtil.getUid(PlatfInterfManager.getInstance().getContext()));
                jb.put(PlatConstant.IWeb.MAC, SharepreferenceUtil.getMac(PlatfInterfManager.getInstance().getContext()));
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
        getWebManager().postData(broadcastName, methodName, jb.toString());
    }

    /**
     * 上传图文
     *
     * @param broadcastName 广播名
     * @param serverName    服务名
     * @param cmdName       接口名（包含路径）
     * @param requestParams 参数
     * @param images        图片文件列表
     * @throws RemoteException 错误
     */
    public static void uploadPramsAndImages(String serverName, String cmdName, Map<String, String> requestParams, List<File> images, String broadcastName)
            throws RemoteException {
        Uri.Builder builder = Uri.parse(cmdName).buildUpon();
        for (String key : requestParams.keySet()) {
            builder.appendQueryParameter(key, requestParams.get(key));
        }
        StringBuilder paths = new StringBuilder();
        if (null != images) {
            for (File file : images) {
                paths.append(file.getAbsolutePath()).append(";");
            }
            int lastIndex = paths.lastIndexOf(";");
            if (lastIndex != -1) {
                paths.replace(lastIndex, lastIndex + 1, "");
            }
        }
        LogPrintUtils.d("uploadPramsAndImages：builder" + builder.toString());
        getWebManager().uploadPramsAndImages(broadcastName, PlatConstant.IWeb.REQ_HTTP_FILES, serverName, builder.toString(), paths.toString());

    }


    /**
     * 上传图片
     *
     * @param broadcastName 广播名
     * @param app_no        工单名
     * @param app_type      工单类型
     * @param imgs          图片信息
     * @param filePaths     图片文件路径
     * @throws RemoteException 错误
     */
    public static void upFileImg(String app_no, String app_type, String imgs, List<File> filePaths, String broadcastName) throws RemoteException {
        StringBuilder paths = new StringBuilder();
        if (null != filePaths) {
            for (File file : filePaths) {
                paths.append(file.getAbsolutePath()).append(";");
            }
            int lastIndex = paths.lastIndexOf(";");
            if (lastIndex != -1) {
                paths.replace(lastIndex, lastIndex + 1, "");
            }
        }

        getWebManager().upFileImg(broadcastName, app_no, app_type, imgs, paths.toString());
    }

    /**
     * 保存单户装拆文件和数据
     *
     * @param broadcastName 广播名
     * @param input         数据
     * @param filePaths     文件路径(多数据集)
     * @throws RemoteException 错误
     */
    public static void saveSBZC(String input, String filePaths, String broadcastName) throws RemoteException {
        getWebManager().saveSBZC(broadcastName, input, filePaths);
    }

    /**
     * @param methodName    方法名
     * @param requestParams 参数
     * @param listener      成功失败监听
     * @throws RemoteException 错误 异常
     */
    protected static void postDataCallback(String methodName, String requestParams, IHttpCallbackInterface listener) throws RemoteException {
        getWebManager().postDataCallback(methodName, requestParams, listener);
    }

    /**
     * @param broadcastName 广播名
     * @param url           地址
     * @throws RemoteException 错误
     */
    public static void requestCustomerUrl(String url, String broadcastName) throws RemoteException {
        getWebManager().requestCustomerUrl(broadcastName, url);
    }

    /**
     * @param type          0不使用进度参数  1使用进度参数
     * @param broadcastName 广播名
     * @param serverName    服务名
     * @param functionName  处理人
     * @param fileId        id
     * @param fileName      文件名
     * @throws RemoteException 错误
     */
    public static void downloadComm(int type, String serverName, String functionName, String fileId, String fileName, String broadcastName) throws RemoteException {
        getWebManager().downloadComm(type, broadcastName, serverName, functionName, fileId, fileName);
    }

    /**
     * @param broadcastName 广播名
     * @param fileUrl       文件地址
     * @param filePath      路径
     * @throws RemoteException 错误
     */
    public static void downloadFile(String fileUrl, String filePath, String broadcastName) throws RemoteException {
        getWebManager().downloadFile(broadcastName, fileUrl, filePath);
    }

    /**
     * @param broadcastName 广播名
     * @param type          类型
     * @param serverName    服务名
     * @param fileId        文件id
     * @param fileName      文件名
     * @throws RemoteException 错误
     */
    public static void downloadFile2(int type, String serverName, String fileId, String fileName, String broadcastName) throws RemoteException {
        getWebManager().downloadFile2(broadcastName, type, serverName, fileId, fileName);
    }


    /**
     * @param broadcastName 广播名
     * @throws RemoteException 错误
     */
    protected static void cancle(String broadcastName) throws RemoteException {
        getWebManager().cancle(broadcastName);
    }

    /**
     * @param broadcastName 广播名
     * @throws RemoteException 错误
     */
    protected static void getLoginHandsetDate(String broadcastName) throws RemoteException {
        getWebManager().getLoginHandsetDate(broadcastName);
    }

    /**
     * @param broadcastName 广播名
     * @throws RemoteException 错误
     */
    protected static void logout(String broadcastName) throws RemoteException {
        getWebManager().logout(broadcastName);
    }

    /**
     * @param broadcastName 广播名
     * @param app_no        工单号
     * @param app_type      类型
     * @param imgs          图片
     * @param filePaths     文件路径
     * @throws RemoteException 错误
     */
    public static void upFileImg2(String app_no, String app_type, String imgs, String filePaths, String broadcastName) throws RemoteException {
        getWebManager().upFileImg2(broadcastName, app_no, app_type, imgs, filePaths);
    }

    /**
     * @param broadcastName 广播名
     * @param meetingId     id
     * @param orderIds      工单ids
     * @param filePaths     文件路径
     * @throws RemoteException 错误
     */
    public static void saveGQH(String meetingId, String orderIds, String filePaths, String broadcastName) throws RemoteException {
        getWebManager().saveGQH(broadcastName, meetingId, orderIds, filePaths);
    }

    /**
     * 保存模块信息
     *
     * @param broadcastName        广播名
     * @param assetNo              设备资产编号
     * @param deviceType           设备类型
     * @param oldModuleNum         旧模块厂商名称
     * @param oldModuleTypeNo      旧模块类型编号
     * @param oldModuleFactoryName 旧模块编号
     * @param newModuleFactoryNo   新模块厂商编号
     * @param newModuleFactoryName 新模块厂商名称
     * @param newModuleNum         新模块编号
     * @param reason               更换原因
     * @param images               更换图示集合
     * @param testResult           召测结果
     * @param operUSERNO           更换人
     * @param operDT               更换时间
     * @throws RemoteException 错误
     */
    public static void setModuleInfo(String assetNo, String deviceType, String oldModuleNum, String oldModuleTypeNo, String oldModuleFactoryName, String newModuleTypeNo, String newModuleFactoryNo, String newModuleFactoryName, String newModuleNum, String reason, String images, String testResult, String operUSERNO, String operDT, String broadcastName) throws RemoteException {
        getWebManager().setModuleInfo(broadcastName, assetNo, deviceType, oldModuleNum, oldModuleTypeNo, oldModuleFactoryName, newModuleTypeNo, newModuleFactoryNo, newModuleFactoryName, newModuleNum, reason, images, testResult, operUSERNO, operDT);
    }

    /**
     * 保存模块信息
     *
     * @param broadcastName        广播名
     * @param assetNo              设备资产编号
     * @param deviceType           设备类型
     * @param oldModuleNum         旧模块厂商名称
     * @param oldModuleTypeNo      旧模块类型编号
     * @param oldModuleFactoryName 旧模块编号
     * @param newModuleFactoryNo   新模块厂商编号
     * @param newModuleFactoryName 新模块厂商名称
     * @param newModuleNum         新模块编号
     * @param reason               更换原因
     * @param images               更换图示集合
     * @param testResult           召测结果
     * @param operUSERNO           更换人
     * @param operDT               更换时间
     * @throws RemoteException 错误
     */
    public static void setModuleInfoNew(String assetNo, String deviceType, String oldModuleNum, String oldModuleTypeNo, String oldModuleFactoryName, String newModuleTypeNo, String newModuleFactoryNo, String newModuleFactoryName, String newModuleNum, String reason, String images, String testResult, String operUSERNO, String operDT, String broadcastName) throws RemoteException {
        getWebManager().setModuleInfoNew(broadcastName, assetNo, deviceType, oldModuleNum, oldModuleTypeNo, oldModuleFactoryName, newModuleTypeNo, newModuleFactoryNo, newModuleFactoryName, newModuleNum, reason, images, testResult, operUSERNO, operDT);
    }

    /**
     * 下载文件-使用老的前置下载方式
     *
     * @param broadcastName 广播名
     * @param type          类型
     * @param serverName    服务名
     * @param fileId        文件id
     * @param fileName      文件名
     * @param progress      进度
     * @param isCancle      是否取消
     * @throws RemoteException 错误
     */
    protected static void downloadFile3(int type, String serverName, String fileId, String fileName, String progress, boolean isCancle, String broadcastName) throws RemoteException {
        getWebManager().downloadFile3(broadcastName, type, serverName, fileId, fileName, progress, isCancle);
    }

    /**
     * 下载文件-使用老的前置下载方式
     *
     * @param serverName 服务名称
     * @param params     参数集合
     * @param serverName 服务名称
     * @param webMethod  下载服务端使用的方法名称
     * @throws RemoteException 错误
     */
    protected static void downloadFileReal(String params, String serverName, String webMethod, String broadcastName) throws RemoteException {
        getWebManager().downloadFileReal(broadcastName, params, serverName, webMethod);
    }

    /**
     * 订阅一个主题，后台根据主题推送消息
     */
    public static boolean subscribe(String packageName, String topic) throws RemoteException {
        return getWebManager().subscribe(packageName, topic);
    }

    /**
     * 向对应的主题，发布一条消息。
     * topic  主题名
     * content 发布的内容
     */
    public static boolean publish(String topic, String content) throws RemoteException {
        return getWebManager().publish(topic, content);
    }

    /**
     * 取消订阅一个主题
     */
    public static boolean unsubscribe(String packageName, String topic) throws RemoteException {
        return getWebManager().unsubscribe(packageName, topic);
    }

    /**
     * 获取离线消息
     * packageName 包名
     */
    public static String getOfflineMsg(String packageName) throws RemoteException {
        return getWebManager().getOfflineMsg(packageName);
    }

    /**
     * 上报已收到消息
     * packageName  包名
     * time 时间戳tag
     */
    public static boolean reportReceivedMsg(String packageName, String time) throws RemoteException {
        return getWebManager().reportReceivedMsg(packageName, time);
    }

    /**
     * 大文件上传
     *
     * @param filePath 上传文件路径
     * @param savePath 服务器保存路径
     * @param isDelete 是否删除
     * @param listener
     * @throws RemoteException
     */
    public static void blockUploadFile(String filePath, String savePath, boolean isDelete, IUploadListener listener)
            throws RemoteException {
        getWebManager().blockUploadFile(filePath, savePath, isDelete, listener);
    }


    /**
     * 取消大文件上传
     *
     * @param filePath 上传文件路径
     * @param savePath 服务器保存路径
     * @param listener
     * @throws RemoteException
     */
    public static void cancelBlockUploadFile(String filePath, String savePath, IHttpCallbackInterface listener)
            throws RemoteException {
        getWebManager().cancelBlockUploadFile(filePath, savePath, listener);
    }

    /**
     * 参数查询接口
     *
     * @param appIdentity       应用标识(APP包名或其它标识)
     * @param paramVersion      参数版本号
     * @param callbackInterface 请求数据的回调
     */
    public static void getParamQuery(String appIdentity, String paramVersion, IHttpCallbackInterface callbackInterface)
            throws RemoteException {
        getWebManager().getParamQuery(appIdentity, paramVersion, callbackInterface);
    }


    /**
     * 文件下载接口(支持多种文件，断点续传)
     * @param filePath           图片在服务端的路径
     * @param savePath           图片在本地保存的路径
     * @param listener  请求数据的回调
     */
    public static void downloadPicFile(String filePath, String savePath, IDownloadListener listener)
            throws RemoteException {
        getWebManager().downloadPicFile(filePath, savePath, listener);
    }

}
